package com.example.calendarprovider;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.calendarprovider.adapter.ResultImageAdapter;
import com.example.calendarprovider.bean.Contact;
import com.example.calendarprovider.bean.ImageItem;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


@RequiresApi(api = Build.VERSION_CODES.M)
public class MainActivity extends AppCompatActivity implements PickConfig.OnImageSelectedFinishListener {


    private static final String TAG = "MainActivity";

    public static final int PERMISSION_REQUEST_CODE = 1;
    private RecyclerView mRecyclerView;
    private ResultImageAdapter mResultImageAdapter;
    //每次选择完后在后面继续添加的图片数据
    private List<ImageItem> DeleteImage = new ArrayList<>();
    //用于拼接重复选择后的图片数据，也就是最终呈现出来的图片，也就是代表总的图片，用于点击删除按钮，因为删除的是在总的数据里面删除
    private List<ImageItem> mAfterImageItem = new ArrayList<>();
    private int i = 0;
    private TextView mSelect_tv;
    private View mContentView;
    private PopupWindow mPopupWindow;
    private Dialog mDialog;
    private View inflate;
    private Button mSendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkCalendarsPermission();
        //queryCanlendars();
        initPickConfig();
        initView();
    }


    //通过单例模式先给他进行赋值
    private void initPickConfig() {
        PickConfig pickConfig = PickConfig.getInstance();
        pickConfig.setMaxSelectCont(9);
        pickConfig.SetOnItemSelectFinishListener(this);
    }


    private void checkCalendarsPermission() {
        int readPermission = checkSelfPermission(Manifest.permission.READ_CALENDAR);
        int writePermission = checkSelfPermission(Manifest.permission.WRITE_CALENDAR);
        int readContactsPermission = checkSelfPermission(Manifest.permission.READ_CONTACTS);
        int readSMSPermission = checkSelfPermission(Manifest.permission.READ_SMS);
        int read_external_storage = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED
                && readContactsPermission == PackageManager.PERMISSION_GRANTED && readSMSPermission == PackageManager.PERMISSION_GRANTED
                && read_external_storage == PackageManager.PERMISSION_GRANTED
        ) {
            //表示有权限
        } else {
            Log.d(TAG, "requestPermission");
            //去获取权限
            //那个提示，用户点击了确定以后再去调用请求权限
            //如果点击了不再提示，就不再获取了
            requestPermissions(new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR,
                    Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.READ_EXTERNAL_STORAGE
            }, PERMISSION_REQUEST_CODE);
        }
    }

    //申请权限后的返回结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            //判断结果
            if (grantResults.length == 4 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED && grantResults[3] == PackageManager.PERMISSION_GRANTED
                    && grantResults[4] == PackageManager.PERMISSION_GRANTED
            ) {
                //有权限
                Log.d(TAG, "has permission ");
            } else {
                Log.d(TAG, "no permission ");
                //没权限
                finish();
            }
        }
    }


//    /**
//     *查询日历表的结构
//     */
//    private void queryCanlendars() {
//        ContentResolver contentResolver = getContentResolver();
//       // Uri uri = Uri.parse("content://" + CalendarContract.AUTHORITY + "/calendars");
//        Uri uri = CalendarContract.Calendars.CONTENT_URI;
//        Cursor query = contentResolver.query(uri, null, null, null, null);
//        String[] columnNames = query.getColumnNames();
//        while (query.moveToNext()){
//            Log.d(TAG, "============");
//            for(String columnName:columnNames){
//                Log.d(TAG, columnName+"===="+query.getString(query.getColumnIndex(columnName)));
//            }
//            Log.d(TAG, "============");
//        }
//    }
//
//    /**
//     * 向日历中添加提醒事件
//     *
//     */
//    public void addAlertEvent(View view){
//        long calID=1;
//        //时间创建
//        Calendar beginTime = Calendar.getInstance();
//        //年/月(从0开始)/日/时/分
//        beginTime.set(2022,10,11,0,0);
//        long beginTimeMills = beginTime.getTimeInMillis();
//        //结束时间
//        Calendar endTime = Calendar.getInstance();
//        endTime.set(2022,10,11,23,59);
//        long endTimeMills = endTime.getTimeInMillis();
//        //事件内容
//        //时间时区
//        String timeZone = TimeZone.getDefault().getID();
//        Log.d(TAG, "timeZone-->"+timeZone);
//        ContentValues eventValues = new ContentValues();
//        //开始时间
//        eventValues.put(CalendarContract.Events.DTSTART,beginTimeMills);
//        //结束时间
//        eventValues.put(CalendarContract.Events.DTEND,endTimeMills);
//        //日历ID
//        eventValues.put(CalendarContract.Events.CALENDAR_ID,calID);
//        //时间时区
//        eventValues.put(CalendarContract.Events.EVENT_TIMEZONE,timeZone);
//        //标题
//        eventValues.put(CalendarContract.Events.TITLE,"双十一购物狂欢开始");
//        //描述
//        eventValues.put(CalendarContract.Events.DESCRIPTION,"尽量把自己想买的东西一口气买完，毫不犹豫");
//        //地点
//        eventValues.put(CalendarContract.Events.EVENT_LOCATION,"茂名");
//        //插入数据
//        Uri eventUri = CalendarContract.Events.CONTENT_URI;
//        //准备好插入事件数据库的内容
//        ContentResolver contentResolver = getContentResolver();
//        //插入数据
//        Uri resultUri = contentResolver.insert(eventUri, eventValues);
//
//        Log.d(TAG, "resultUri-> "+resultUri);
//        String eventId = resultUri.getLastPathSegment();
//        Log.d(TAG, "eventId "+eventId);
//        //插入提醒事件
//        ContentValues reminderValues = new ContentValues();
//        reminderValues.put(CalendarContract.Reminders.EVENT_ID,eventId);
//         //15分钟前进行提醒
//        reminderValues.put(CalendarContract.Reminders.MINUTES,15);
//        reminderValues.put(CalendarContract.Reminders.METHOD,CalendarContract.Reminders.METHOD_ALERT);
//
//        Uri reminderUri=CalendarContract.Reminders.CONTENT_URI;
//        contentResolver.insert(reminderUri,reminderValues);
//    }
//
//    /**
//     * 获取手机联系人信息
//     *
//     */
//    public void getPhoneNumbers(View view){
//        ContentResolver cr = getContentResolver();
//        Uri rowContactsUri = Uri.parse("content://com.android.contacts/raw_contacts");
//        //查询联系人列表所有信息
//        Cursor query = cr.query(rowContactsUri, null, null, null, null);
//        String [] columNames=query.getColumnNames();
//        List<Contact> contacts = new ArrayList<>();
//        while (query.moveToNext()){
//            Contact contact = new Contact();
//            contact.setId(query.getString(query.getColumnIndex("contact_id")));
//            contact.setDisplayName(query.getString(query.getColumnIndex("display_name")));
//            contacts.add(contact);
//            // query.getString(query.getColumnIndex(""))
//            for(String columName:columNames){
//                //打印所有联系人列表表的信息
//                Log.d(TAG, ""+columName+"--->"+query.getString(query.getColumnIndex(columName)));
//            }
//        }
//        query.close();
//        //查询联系人手机号码
//        Uri phoneNumUri = Uri.parse("content://com.android.contacts/data/phones");
//        for(Contact contact:contacts){
//            //姓名，电话在data1列里面，只需查询data1列 ，条件raw_contact_id要等于我们上面的contact.getId()
//            Cursor phoneCursor = cr.query(phoneNumUri, new String[]{"data1"}, "raw_contact_id=?", new String[]{contact.getId()}, null);
//            if(phoneCursor.moveToNext()){
//                contact.setPhoneNum(phoneCursor.getString(phoneCursor.getColumnIndex("data1")).replace("-",""));
//            }
//            //释放资源
//            phoneCursor.close();
//        }
//        //查询获取到的手机联系人id，姓名和手机号码
//        for(Contact contact : contacts) {
//            Log.d(TAG,contact.getId() + " -- NAME --- > " + contact.getDisplayName() + " --- PHONE -- > " + contact.getPhoneNum());
//        }
//    }
//
//    /**
//     * 获取短信内容
//     */
//    public void getSMS(View view){
//        Uri uri = Uri.parse("content://sms/");
//        ContentResolver contentResolver = getContentResolver();
//        //查询短信列表信息
//        Cursor query = contentResolver.query(uri, null, null, null, null);
//        String[] columnNames = query.getColumnNames();
//        while (query.moveToNext()){
//            for(String columnName:columnNames){
//                //打印短信列表字段名和字段内容
//                Log.d(TAG, " "+columnName+"=="+query.getString(query.getColumnIndex(columnName)));
//            }
//        }
//        query.close();
//    }

    /**
     * 获取媒体库信息
     */
    public void getREAD_EXTERNAL_STORAGE(View view) {
        Intent intent = new Intent(MainActivity.this, PickerActivity.class);
        startActivity(intent);
    }

    private void initView() {
        mRecyclerView = findViewById(R.id.result_list);
        mSelect_tv = findViewById(R.id.select_tv);
        mSendButton = findViewById(R.id.send_button);
        mResultImageAdapter = new ResultImageAdapter();
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.setAdapter(mResultImageAdapter);
        //点击加号
        mResultImageAdapter.setOnJiaClickListener(new ResultImageAdapter.onJiaClickListener() {
            @Override
            public void onClickJiaEvent() {
                Intent intent = new Intent(MainActivity.this, PickerActivity.class);
                intent.putExtra("selectSize", mAfterImageItem.size());
                Log.d(TAG, "selectSize " + mAfterImageItem.size());
                startActivity(intent);
            }
        });
        //点击删除
        mResultImageAdapter.setOnDeleteImageListener(new ResultImageAdapter.onDeleteImageListener() {
            @Override
            public void onClickDeleteEvent(int position) {
                Log.d(TAG, "点击删除position: " + position);
                mAfterImageItem.remove(position);
                Log.d(TAG, "点击删除size: " + mAfterImageItem.size());
                mRecyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this, 3));
                //删除数据后更新界面
                mResultImageAdapter.setData(mAfterImageItem, 3, true);
                mResultImageAdapter.notifyDataSetChanged();
            }
        });
        mSelect_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopupWindow();
            }
        });
        //Post+Header
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "\""+ mAfterImageItem.get(0).getPath()+"\"");


//                // File file = new File("/storage/emulated/0/Tencent/QQ_Images/-158f5e71f5d5e1a9.jpg");
//
//                OkHttpClient client = new OkHttpClient.Builder()
//                        .connectTimeout(10000, TimeUnit.MILLISECONDS)
//                        .build();
//
//                MultipartBody.Builder builder = new MultipartBody.Builder();
//                builder.setType(MultipartBody.FORM)
/////                .addPart(
////                        Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileName + "\""),
////                        RequestBody.create(MEDIA_TYPE_PNG, file))
////                .addPart(
////                        Headers.of("Content-Disposition", "form-data; name=\"imagetype\""),
////                        RequestBody.create(null, imageType))
////                .addPart(
////                        Headers.of("Content-Disposition", "form-data; name=\"userphone\""),
////                        RequestBody.create(null, userPhone))
//                        .addFormDataPart("place", "工业区1")
//                        .addFormDataPart("type", "设备损坏")
//                        .addFormDataPart("description", "水管1出现老化");
//                       // .addFormDataPart("file", file.getName(), fileBody)
//
//                MediaType mediaType = MediaType.parse("image/jpeg");
//                for(int i=0;i<mAfterImageItem.size();i++){
//                    File file = new File(mAfterImageItem.get(i).getPath());
//                    RequestBody fileBody=RequestBody.create(file,mediaType);
//                    builder.addFormDataPart("file",file.getName(),fileBody);
//

             //   File file = new File("/storage/emulated/0/Tencent/QQ_Images/-158f5e71f5d5e1a9.jpg");
              //  File file1 = new File("/storage/emulated/0/Pictures/graphSearch/百度图像搜索/20220619222234.jpg");
                MediaType mediaType = MediaType.parse("image/jpeg");
              //  RequestBody fileBody = RequestBody.create(file, mediaType);
              //  RequestBody file1Body = RequestBody.create(file1, mediaType);
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(10000, TimeUnit.MILLISECONDS)
                        .build();
                MultipartBody.Builder builder = new MultipartBody.Builder();

                builder.setType(MultipartBody.FORM)
///                .addPart(
//                        Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileName + "\""),
//                        RequestBody.create(MEDIA_TYPE_PNG, file))
//                .addPart(
//                        Headers.of("Content-Disposition", "form-data; name=\"imagetype\""),
//                        RequestBody.create(null, imageType))
//                .addPart(
//                        Headers.of("Content-Disposition", "form-data; name=\"userphone\""),
//                        RequestBody.create(null, userPhone))
                        .addFormDataPart("place", "工业区1")
                        .addFormDataPart("type", "设备损坏")
                        .addFormDataPart("description", "水管1出现老化");
//                        .addFormDataPart("file", file.getName(), fileBody)
//                        .addFormDataPart("file", file1.getName(), file1Body);
                for(int i=0;i<mAfterImageItem.size();i++){

                    File file=new File( mAfterImageItem.get(i).getPath());
                    RequestBody fileBody = RequestBody.create(file, mediaType);
                    builder.addFormDataPart("file", file.getName(), fileBody);
                    Log.d(TAG, "onClick:上传的图片信息 "+mAfterImageItem.get(i).getPath());
                }

//                //post请求
//                FormBody formBody = new FormBody.Builder()
//                        .add("place", "工业区1")
//                        .add("type", "设备损坏")
//                        .add("description", "水管1出现老化")
//                        .add("file", String.valueOf(file))
//
//                        .build();
                Request request = new Request.Builder().url("http://121.5.175.104:8080/hitch").
                        addHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJleHAiOjE2NTY1ODEwNjgsInVzZXJJZCI6IjIiLCJpYXQiOjE2NTU5NzYyNjgsInVzZXJuYW1lIjoiYWRtaW4ifQ.8HDt3Ecp04nrpZCQFf81Y82sly3e3b9XMyAMPY4NSmL_0vuds0soKXpoX2lxVhZJwMx1YqCCf_9zawgkS-BebA")
                        .post(builder.build()).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.d(TAG, "onFailure: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        if (response.code() >= 200) {
                            Log.d(TAG, "onResponse: 网络请求成功");
                            String result = response.body().string();
                            Log.d(TAG, "onResponse:" + result);

                        }
                    }
                });
                Toast.makeText(MainActivity.this, "上传故障成功", Toast.LENGTH_SHORT).show();
                finish();
            }

        });

    }

    private void initPopupWindow() {
//        mContentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.guzhang_type, null, false);
//        mPopupWindow = new PopupWindow(mContentView, LinearLayout.LayoutParams.MATCH_PARENT,
//                LinearLayout.LayoutParams.MATCH_PARENT);
//        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
//        mPopupWindow.setOutsideTouchable(true);
//        mPopupWindow.setTouchable(true);
//        mPopupWindow.setAnimationStyle(R.style.my);
        //        Log.d("====", "showMainActivity: "+instance);
//        Toast.makeText(MainUnityActivity.this,"=====",Toast.LENGTH_SHORT).show();
        mDialog = new Dialog(this, R.style.BottomDialog);
        //填充对话框的布局
        inflate = LayoutInflater.from(this).inflate(R.layout.guzhang_type, null);
        //初始化控件
        //
        //将布局设置给Dialog
        mDialog.setContentView(inflate);
//                //获取当前Activity所在窗体
//                Window dialogWindow = mDialog.getWindow();
//                //设置Dialog从窗体底部弹出
//                dialogWindow.setGravity(Gravity.BOTTOM);
//                //获得窗体的属性
//                WindowManager.LayoutParams lp= dialogWindow.getAttributes();
//                //设置Dialog距离底部的距离
//                lp.y=20;
//                //将属性设置给窗体
//                dialogWindow.setAttributes(lp);
        //显示对话框
//                mDialog.show();
        ViewGroup.LayoutParams layoutParams = inflate.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        inflate.setLayoutParams(layoutParams);
        mDialog.getWindow().setGravity(Gravity.BOTTOM);
        mDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        mDialog.show();
        mDialog.getWindow().findViewById(R.id.device_old).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelect_tv.setText("设备老化");
                Toast.makeText(MainActivity.this, "故障类型为设备老化", Toast.LENGTH_SHORT).show();
            }
        });
        mDialog.getWindow().findViewById(R.id.device_lose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelect_tv.setText("设备丢失");
                Toast.makeText(MainActivity.this, "故障类型为设备丢失", Toast.LENGTH_SHORT).show();
            }
        });
        mDialog.getWindow().findViewById(R.id.device_damage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelect_tv.setText("设备损坏");
                Toast.makeText(MainActivity.this, "故障类型为设备损坏", Toast.LENGTH_SHORT).show();
            }
        });
        mDialog.getWindow().findViewById(R.id.operation_exception).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelect_tv.setText("设备异常");
                Toast.makeText(MainActivity.this, "故障类型为设备异常", Toast.LENGTH_SHORT).show();
            }
        });
        mDialog.getWindow().findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

//    public void sendToGuZhang(View view){
//       // Log.d(TAG, "最终的数据"+mAfterImageItem);
////        //将数据发送给后台
////        OkHttpClient client = new OkHttpClient().newBuilder().
////                connectTimeout(10000, TimeUnit.MILLISECONDS).
////                build();
////        //要提交的内容
////        Gson gson = new Gson();
////        String json = gson.toJson(mAfterImageItem);
////        Log.d(TAG, "json 数据"+json);
//        OkHttpClient client = new OkHttpClient();
//        //post请求
//        FormBody formBody = new FormBody.Builder()
//                .add("place", "工业区1")
//                .add("type", "设备损坏")
//                .add("description", "水管1出现老化")
//                .add("file", "/storage/emulated/0/Tencent/QQ_Images/-158f5e71f5d5e1a9.jpg")
//                .build();
//        Request request = new Request.Builder().url("http://121.5.175.104:8080/hitch").
//                addHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJleHAiOjE2NTUxMjYyNTEsInVzZXJJZCI6IjIiLCJpYXQiOjE2NTQ1MjE0NTEsInVzZXJuYW1lIjoiYWRtaW4ifQ.VbOGVI-Sz4vthNrqlsyx-5FQB8mJEWH-AouLNUx6d6odrKwgNdR-7DvzdYu4sY_Ch6WitL02qwQlYT23rWKrBw")
//                .post(formBody).build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                Log.d(TAG, "onFailure: "+e.getMessage());
//            }
//
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//              if(response.code()==200){
//                  Log.d(TAG, "onResponse: 网络请求成功");
//                  String result = response.body().string();
//                  Log.d(TAG, "onResponse:"+result);
//              }
//            }
//        });
//      // Toast.makeText(MainActivity.this,"上报故障数据成功",Toast.LENGTH_SHORT).show();
//    }


    //点击完成的回调函数
    @Override
    public void onSelectFinished(List<ImageItem> result) {
        //每次选后都需要加进去，因为这个代表总的图片数据
        mAfterImageItem.addAll(result);
        Log.d(TAG, "onSelectFinished: 进来了");
        //需要清除重新加入，因为这是重新加入图片，不能重复，不删掉的话会把之间已经添加的图片也一起添加
        DeleteImage.clear();
        //所选择的数据回来
        for (ImageItem imageItem : result) {
            Log.d(TAG, "item--->" + imageItem);
            DeleteImage.add(imageItem);
        }


        int horizontalCount;
//        if(result.size()<3){
//            horizontalCount=result.size();
//        }else {
//            horizontalCount=3;
//        }
        horizontalCount = 3;
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, horizontalCount));
        //
        mResultImageAdapter.setData(DeleteImage, horizontalCount, false);
        Log.d(TAG, "onSelectFinished: " + mAfterImageItem);

    }
}